package com.bbs.controller;

import com.bbs.entity.ResultInfo;
import com.bbs.entity.User;
import com.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private UserService userService;
    /**
     * 去注册和登录的页面
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public ResultInfo register(@RequestBody User user, HttpServletResponse resp) throws Exception{
        ResultInfo resultInfo = new ResultInfo();
        int flag = userService.register(user);
        if (flag == 1) {
            resultInfo.setCode("0");
            resultInfo.setMsg("注册成功，请激活后登录");
        }else if (flag == 2){
            resultInfo.setCode("2");
            resultInfo.setMsg("邮箱被占用");
        }else {
            resultInfo.setCode("1");
            resultInfo.setMsg("注册失败，请重新注册");
        }
        return resultInfo;
    }
    @RequestMapping("/tse")
    @ResponseBody
    public String update(HttpServletRequest req){
        String code = req.getParameter("code");
        userService.update(code);
        return "激活成功，请<a href='http://localhost:8080/ssm_bbs_war_exploded/toLogin#'>登录</a>";
    }
    /**
     * 登录
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public ResultInfo doLogin(@RequestBody User user, HttpSession session) {
        System.out.println(user.getEmail() + "--" + user.getPassword());
        //调用service方法校验邮箱和密码
        User exitUser = userService.checkPassword(user);
        ResultInfo resultInfo = new ResultInfo();
        if (Objects.nonNull(exitUser) && exitUser.getId() != 0 && exitUser.getActived() != 0) {
            session.setAttribute("uid", exitUser.getId());
            session.setAttribute("headUrl", exitUser.getHeadUrl());
            resultInfo.setCode("0");
            resultInfo.setMsg("登录成功");
        }else {
            resultInfo.setCode("1");
            resultInfo.setMsg("登录失败");
        }
        return resultInfo;
    }
/*
* 退出
* @param session
* @return
*/
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();//销毁session
        return "login";
    }
}
